package com.woniuxy.controller;

import cn.hutool.core.io.FileUtil;
import com.woniuxy.entity.Blog;
import com.woniuxy.entity.DTO.BlogSearchDTO;
import com.woniuxy.service.BlogService;
import com.woniuxy.utils.PageResult;
import com.woniuxy.utils.ResponseResult;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@RestController
@RequestMapping("/life/blog")
public class BlogController {
    @Autowired
    private BlogService blogServiceImpl;

    /*
     * 根据分类id查询所有该类博客
     * */
    @GetMapping("/findBlogByTypeId")
    public ResponseResult<PageResult> findBlogByTypeId(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam("typeId") Integer typeId){
        System.out.println("typeId::::::::::::::::::::::::::::::::::::::::::"+ typeId);
        if (typeId == 0) {
            PageResult result = blogServiceImpl.findBlogByTypeId(pageNum, pageSize,null);
            System.out.println("result::::::::::::::::::::::::::::::::::::::::::"+ result.getList());
            return ResponseResult.success(result);
        } else {
            PageResult result = blogServiceImpl.findBlogByTypeId(pageNum, pageSize,typeId);
            System.out.println("result::::::::::::::::::::::::::::::::::::::::::"+ result.getList());
            return ResponseResult.success(result);
        }
    }

    /*
    * 根据博客标题搜索博客
    * */
    @PostMapping("/search")
    public ResponseResult<PageResult> search(@RequestBody  BlogSearchDTO dto) {
        System.out.println("收到的BlogSearchDTO对象"+dto);
        PageResult result = blogServiceImpl.search(
                dto.getPageNum(),
                dto.getPageSize(),
                dto.getBlogName()
        );
        return ResponseResult.success(result);
    }

    /*
    * 查询用户发布的所有blog
    * */
    @GetMapping("/findUserBlog")
    public ResponseResult<PageResult> findUserBlog(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam("userId") Integer userId){
        PageResult result = blogServiceImpl.findUserBlog(pageNum, pageSize, userId);
        return ResponseResult.success(result);
    }

    /*
    * 查询用户收藏的所有blog
    * */
    @GetMapping("/findUserCollectBlog")
    public ResponseResult<PageResult> findUserCollectBlog(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam("userId") Integer userId){
        PageResult result = blogServiceImpl.findUserCollectBlog(pageNum, pageSize, userId);
        return ResponseResult.success(result);
    }

    /*
    * 上传文件
    * */
    @PostMapping("/upload")
    public ResponseResult<String> upload(@RequestParam("file") MultipartFile file ) throws Exception{
        System.out.println("客户端传入的file"+ file);
        // 先拿到项目根路径（假设项目根就是 smart-elderlycare-platform 所在路径）
        String projectRoot = System.getProperty("user.dir");
        // 拼接 life-service 模块路径，根据实际目录结构调整，比如 service 下直接是 life-service
        String lifeServiceDir = projectRoot + "/service/life-service";
        System.out.println("life-service 目录路径：" + lifeServiceDir);
        // 拼接 life-service 模块下的 file 文件夹路径
        String fileDir = lifeServiceDir + "/file/";
        if (!FileUtil.isDirectory(fileDir)){
            FileUtil.mkdir(fileDir);
        }
        byte[] bytes = file.getBytes();
        String fileName = System.currentTimeMillis() + "_" +file.getOriginalFilename();
        //写入文件
        FileUtil.writeBytes(bytes, fileDir + fileName);
        String url = "http://localhost:8086/life/blog/download/" + fileName;
        return ResponseResult.success(url);
    }

    /*
    * 下载文件
    * */
    @GetMapping("/download/{fileNme}")
    public void download(@PathVariable("fileNme") String fileNme, HttpServletResponse response) throws Exception{
        // 先拿到项目根路径（假设项目根就是 smart-elderlycare-platform 所在路径）
        String projectRoot = System.getProperty("user.dir");
        // 拼接 life-service 模块路径，根据实际目录结构调整，比如 service 下直接是 life-service
        String lifeServiceDir = projectRoot + "/service/life-service";
        System.out.println("life-service 目录路径：" + lifeServiceDir);
        // 拼接 life-service 模块下的 file 文件夹路径
        String fileDir = lifeServiceDir + "/file/";
        // 拼接 fileName
        String filePath = fileDir + fileNme;
        // 判断文件是否存在
        boolean exists = FileUtil.exist(filePath);
        if (!exists){
            throw new RuntimeException("文件不存在");
        }
        // 读取文件字节流
        byte[] bytes = FileUtil.readBytes(filePath);
        // 获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        // 输出流对象把文件写出到客户端
        os.write(bytes);
        os.flush();
        os.close();
    }

    /*
    * 添加博客 图片类型
    * */
    @PostMapping("/addImg")
    public ResponseResult<Integer> add(@RequestBody Blog blog){
        blog.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println(blog);
        int id = blogServiceImpl.add(blog);
        return ResponseResult.success("添加成功", id);
    }

    @PostMapping("/addVideo")
    public ResponseResult<Integer> addVideo(@RequestBody Blog blog){
        blog.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println(blog);
        int id = blogServiceImpl.addVideo(blog);
        return ResponseResult.success("添加成功", id);
    }


    /*
    * 统计用户发布的博客数量
    * */
    @GetMapping("/publishCount")
    public ResponseResult<Integer> publishCount(@RequestParam("userId") Integer userId){
        Integer publishCount = blogServiceImpl.publishCount(userId);
        return ResponseResult.success(publishCount);
    }

}
